//
//  PublishController.m
//  QQplayground
//
//  Created by zhangxy on 2018/5/22.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "PublishController.h"
#import "ZTextView.h"
#import "ChooseTypeController.h"
#import "ChooseLabelController.h"
#import "NavTypeEntity.h"

#import "MyButton.h"
#import "XHImageViewer.h"

#import "RITLPhotos.h"

#import "UIView+Border.h"
#import "LoginController.h"
@interface PublishController ()<ImagePickerDelegate,UITextViewDelegate,RITLPhotosViewControllerDelegate>{
    UIButton *curBtn;
    
    NavTypeEntity *checkType;
    BOOL isSend;
}

@property(nonatomic,strong) UIView *conentView;
@property(nonatomic,strong) ZTextView *titleView;

@property(nonatomic,strong) UIScrollView *mainScroll;
@property(nonatomic,strong) UIView *menuScroll;
@property(nonatomic,strong) NSMutableDictionary *photos;
@property(nonatomic,strong) NSMutableArray *waitUploadData;
@property(nonatomic,strong) NSMutableArray *labels;

@end

@implementation PublishController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.title = @"";
    [self setNavigationBar];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,56,26)];
    [button setBackgroundColor:UIColorFromRGBAlpha(TextWhiteColor, 0.3)];
    [button setTitle:@"发布" forState:0];
    [button.titleLabel setFont:FontFiftent];
    button.layer.cornerRadius = 8.0f;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(publishAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = btn;
    self.navigationController.navigationBarHidden = NO;
    
    _photos = [[NSMutableDictionary alloc] init];
    _labels = [[NSMutableArray alloc] init];
    _waitUploadData = [[NSMutableArray alloc] init];
    
    if(_type == 2){
        checkType = [[NavTypeEntity alloc] init];
        checkType.nav_type = @"mimi";
        checkType.nav_name = @"帖子";
        checkType.nav_id  = @"0";
    }
    if(_type == 2){
        checkType = [[NavTypeEntity alloc] init];
        checkType.nav_type = @"forum";
        checkType.nav_name = @"秘密";
        checkType.nav_id  = @"0";
    }
    
    [self createViewByType];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allHideKeyBoard)];
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:tap];
    if (![UserUtil getUser].isOnline){
        [self showLogin];
        return;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
    
}

-(void)publishAction{
    // 发布
    // 素材
    if(_type == 1){
        if(checkType == nil){
            [PopUtil showMessage:@"请选项分类" positionType:PopPositionTypeMiddle];
            return;
        }
        
        if(_labels.count == 0){
            [PopUtil showMessage:@"请选项标签" positionType:PopPositionTypeMiddle];
            return;
        }
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self uploadImages];
    }
}


-(void)publishSucai{
    NSString *strTag = @"";
    for (NavTypeEntity *tagItem in _labels) {
        strTag = [strTag stringByAppendingFormat:@"%@,",tagItem.tag_id];
    }
    if(strTag.length>0){
        strTag = [strTag substringToIndex:strTag.length - 1];
    }
    
    NSString *str = @"";
    for (NSDictionary *dict in _photos.allValues) {
        str = [str stringByAppendingFormat:@"%@,",dict[@"image_id"]];
    }

    if(str.length>0){
        str = [str substringToIndex:str.length - 1];
    }
    
    if([self sendNamedMessage:strTag]){
        return ;
    }
    
    if(isSend){
        return;
    }
    
    isSend = true;
    
    NSString *nav_type = self->checkType.nav_type;
    if([@"skin" isEqual:nav_type]){
        nav_type = @"skins";
    }
    [NetworkUtil POST:API_publishImage(convertToString(nav_type)) parameters:@{@"session_uid":[UserUtil getUser].user_id,
                                                                                         @"title":convertToString(_titleView.text),
                                                                                         @"cat_id":checkType.cat_id,
                                                                                         @"tag_id": strTag,
                                                                                         @"img_id":str
                                                                                         } success:^(id responseObject, NSDictionary *dict) {
                                                                                             [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                                                             [PopUtil showMessage:dict[@"msg"]];
                                                                                             [self backAction];
                                                                                         } failure:^(NSError *error, NSString *message) {
                                                                                             [MBProgressHUD hideHUDForView:self.view animated:YES];
                                                                                             [PopUtil showMessage:message];
                                                                                             self->isSend =false;
                                                                                         }];
}

-(BOOL)sendNamedMessage:(NSString *)strTag{
    if([@"name" isEqual:checkType.nav_type] || [@"group" isEqual:checkType.nav_type] || [@"sign" isEqual:checkType.nav_type] ){
        NSString *message1 = @"";
        NSString *message2 = @"";
        if([@"name" isEqual:checkType.nav_type] || [@"sign" isEqual:checkType.nav_type]){
            ZTextView *text1 = [_conentView viewWithTag:1];
            if(text1 && convertToString(text1.text).length>0) {
                message1 = convertToString(text1.text);
            }
            ZTextView *text2 = [_conentView viewWithTag:2];
            if(text2 && convertToString(text2.text).length>0) {
                message2 = convertToString(text2.text);
            }
        }
        
        if([@"group" isEqual:checkType.nav_type]){
            UIView *g1 = [_conentView viewWithTag:1111];
            int i=1;
            for(UIView *itemView in g1.subviews){
                ZTextView *vText = [itemView viewWithTag:itemView.tag+1000];
                if(vText!=nil && [vText isKindOfClass:[UITextView class]]){
                    if(convertToString(vText.text).length > 0){
                        message1 = [message1 stringByAppendingFormat:@"\n%@",convertToString(vText.text)];
                    }
                }
                i ++ ;
            }
            
            UIView *g2 = [_conentView viewWithTag:2222];
            int j=1;
            for(UIView *itemView in g2.subviews){
                ZTextView *vText = [itemView viewWithTag:itemView.tag+1000];
                if(vText!=nil && [vText isKindOfClass:[ZTextView class]]){
                    if(convertToString(vText.text).length > 0){
                        message2 = [message2 stringByAppendingFormat:@"\n%@",convertToString(vText.text)];
                    }
                }
                j ++ ;
            }
            
            if(message1.length == 0 || message1.length == 0){
                [PopUtil showMessage:@"请填写完整" positionType:PopPositionTypeMiddle];
                return YES;
            }
            
            if(message1.length > 2){
                message1 = [message1 substringFromIndex:1];
            }
            
            if(message2.length > 2){
                message2 = [message2 substringFromIndex:1];
            }
            
        }
        
        if(isSend){
            return YES;
        }
        
        isSend = true;
        
        [NetworkUtil POST:API_publishImage(convertToString(checkType.nav_type))
               parameters:@{
                            @"session_uid":[UserUtil getUser].user_id,
                            @"title":convertToString(_titleView.text),
                            @"cat_id":checkType.cat_id,
                            @"tag_id": strTag,
                            @"message_1":message1,
                            @"message_2":message2
                         } success:^(id responseObject, NSDictionary *dict) {
                             [MBProgressHUD hideHUDForView:self.view animated:YES];
                             [PopUtil showMessage:dict[@"msg"]];
                             [self backAction];
                         } failure:^(NSError *error, NSString *message) {
                             [MBProgressHUD hideHUDForView:self.view animated:YES];
                             [PopUtil showMessage:message];
                             
                             self->isSend = false;
                             
                         }];
        
        return YES;
    }
    return NO;
}


-(void)createViewByType{
    if(_type == 3){
        UIImageView *bgView = [self createImageView];
        [bgView setBackgroundColor:UIColorFromRGB(PublishBgColor)];
        [bgView setFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        [self.view addSubview:bgView];
        
        UILabel *lab = [self createLabel];
        
        [lab setFrame:CGRectMake(20, 0, ScreenWidth - 40, 44)];
        [lab setFont:FontFiftent];
        [lab setTextColor:UIColorFromRGB(TextSizeEightColor)];
        [lab setBackgroundColor:UIColor.clearColor];
        [lab setFont:FontThirteen];
        [lab setText:@"除了你自己，没有人会知道你的身份"];
        [self.view addSubview:lab];
    }else{
        
        _titleView = [self createTextView];
        _conentView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-30, 64)];
        [_titleView setFrame:self.conentView.bounds];
        [_conentView addSubview:_titleView];
        
        [self.view addSubview:_conentView];
        if(_type == 1){
            [self.titleView setPlaceholder:Uninput_material];
        }else if(_type == 2){
            [self.titleView setPlaceholder:Uninput_invitation];
        }
        [self.titleView setFrame:CGRectMake(0, 10, ScreenWidth - 30, 44)];
    }
    
    
    
    if(_type != 3){
        _mainScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 60, ScreenWidth, 108)];
        [_mainScroll setBackgroundColor:[UIColor clearColor]];
        [self.view addSubview:_mainScroll];
        
        _mainScroll.showsHorizontalScrollIndicator = NO;
        _mainScroll.showsVerticalScrollIndicator = NO;
        _mainScroll.alwaysBounceHorizontal = YES;
        _mainScroll.alwaysBounceVertical = NO;
        _mainScroll.pagingEnabled = NO;
    //    _mainScroll.bounces = NO;
        _mainScroll.scrollEnabled = YES;
        
        
        [self createShareButton:(int)_waitUploadData.count + 1];
    }
    
    
    CGFloat y = 234;
    
    _menuScroll = [[UIView alloc]initWithFrame:CGRectMake(0, y, ScreenWidth, 108)];
    [_menuScroll setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_menuScroll];
    
 
    if(_type == 1 || _type == 2){
        UIButton *btn = [self createButton];
        btn.layer.cornerRadius = 8.0f;
        btn.layer.masksToBounds = YES;
        btn.layer.borderWidth = 1.0f;
        btn.layer.borderColor = UIColorFromRGB(BgTitleColor).CGColor;
        [btn setFrame:CGRectMake(20, 0, 88, 30)];
        btn.tag = 1;
        [btn setTitle:@"选择分类" forState:0];
        if(_type == 2){
            [btn setTitle:@"选择话题" forState:0];
            btn.tag = 3;
        }
        [btn setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
        [btn addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.menuScroll addSubview:btn];
    }
    if(_type == 3 || _type == 1){
        UIButton *btn2 = [self createButton];
        btn2.layer.cornerRadius = 8.0f;
        btn2.layer.masksToBounds = YES;
        btn2.layer.borderWidth = 1.0f;
        [btn2 setTitle:@"添加标签" forState:0];
        [btn2 setTitleColor:UIColorFromRGB(TextLinkColor) forState:0];
        btn2.layer.borderColor = UIColorFromRGB(BgListSectionColor).CGColor;
        [btn2 setFrame:CGRectMake(118, 0, 88, 30)];
        btn2.tag = 2;
        [btn2 addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.menuScroll addSubview:btn2];
        
        if(_type == 3){
            [btn2 setFrame:CGRectMake(20, 0, 88, 30)];
            
            UIButton *btn = [self createButton];
            btn.layer.cornerRadius = 8.0f;
            btn.layer.masksToBounds = YES;
            btn.layer.borderWidth = 1.0f;
            btn.layer.borderColor = UIColorFromRGB(BgTitleColor).CGColor;
            [btn setFrame:CGRectMake(118, 0, 88, 30)];
            [btn setTitle:@"公开" forState:0];
            btn.tag = 4;
            [btn setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
            [btn addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.menuScroll addSubview:btn];
        }
    }
    
    if(_type == 3){
        [self.view addSubview:self.titleView];
        [self.titleView setPlaceholder:Uninput_secret];
    }
}


- (ZTextView *)createTextView
{
    ZTextView  *textView = [[ZTextView alloc] init];
    textView.frame = CGRectMake(15,64,SCREEN_WIDTH - 30, 140);
//        _textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5);
    textView.placeholder = self.navigationItem.title;
    textView.placeholderColor = LIGHT_GRAY_COLOR;
    textView.textColor = UIColorFromRGB(TextSizeEightColor);
    textView.delegate = self;
    textView.font = FontFiftent;
    //        _textView.inputAccessoryView = self.keyboardView;
    textView.showsVerticalScrollIndicator = NO;
//    [textView becomeFirstResponder];  //弹出键盘
    return textView;
}

-(void)changeSelectType{
    if([@"name" isEqual:checkType.nav_type] || [@"sign" isEqual:checkType.nav_type]){
        _mainScroll.hidden = YES;
        
        
        [_conentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        ZTextView *textView1 = [self createTextView];
        [textView1 setFrame:CGRectMake(0, 10, ScreenWidth - 30, 40)];
        [textView1 addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
        [textView1 setPlaceholder:[NSString stringWithFormat:@"填写%@",checkType.nav_name]];
        textView1.tag = 1;
        [_conentView addSubview:textView1];
        
        [_conentView setFrame:CGRectMake(15, 0, ScreenWidth - 15, 60)];
        
        
        if([@"情侣" isEqual:checkType.cat_name]){
            [textView1 setFrame:CGRectMake(34, 10, ScreenWidth - 30 - 34, 40)];
            
            ZTextView *textView2 = [self createTextView];
            [textView2 setFrame:CGRectMake(34, 70, ScreenWidth - 30 - 34, 40)];
            [textView2 addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
            [textView2 setPlaceholder:[NSString stringWithFormat:@"填写%@",checkType.nav_name]];
            textView2.tag = 2;
            [_conentView addSubview:textView2];
            
            UIImageView *imgView  = [self createImageView];
            [imgView setFrame:CGRectMake(0, 0, 34, 120)];
            [imgView setContentMode:UIViewContentModeCenter];
            [imgView setImage:[UIImage imageNamed:@"情侣"]];
            [_conentView addSubview:imgView];
            
            [_conentView setFrame:CGRectMake(15, 0, ScreenWidth - 15, 120)];
            [_menuScroll setFrame:CGRectMake(0, CGRectGetMaxY(_conentView.frame) + 10, ScreenWidth, 108)];
        }
    }
    if([@"group" isEqual:checkType.nav_type]){
        _mainScroll.hidden = YES;
        [_conentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        UIView *g1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 30, 120)];
        g1.tag = 1111;
        
        UIView *item1 = [self createGroupItem:1];
        [item1 setFrame:CGRectMake(0, 0, ScreenWidth - 30, 60)];
        UIButton *btn = [self createAddButton];
        btn.tag = 11111;
        [btn setFrame:CGRectMake(0, 60, ScreenWidth - 30, 60)];
        
        [g1 addSubview:item1];
        [g1 addSubview:btn];
        [_conentView addSubview:g1];
        
        [_conentView setFrame:CGRectMake(15, 0, ScreenWidth - 15, 120)];
        [_menuScroll setFrame:CGRectMake(0, CGRectGetMaxY(_conentView.frame) + 10, ScreenWidth, 108)];
        
        if([@"情侣" isEqual:checkType.cat_name]){
            UIView *g2 = [[UIView alloc] initWithFrame:CGRectMake(0, 120, ScreenWidth - 30, 120)];
            g2.tag = 2222;
            
            UIView *item2 = [self createGroupItem:1];
            [item2 setFrame:CGRectMake(0, 0, ScreenWidth - 30, 60)];
            UIButton *btn2 = [self createAddButton];
            [btn2 setFrame:CGRectMake(0, 60, ScreenWidth - 30, 60)];
            
            [g2 addSubview:item2];
            [g2 addSubview:btn2];
            btn2.tag = 22222;
            [_conentView addSubview:g2];
            
            [_conentView setFrame:CGRectMake(15, 0, ScreenWidth - 15, 240)];
            [_menuScroll setFrame:CGRectMake(0, CGRectGetMaxY(_conentView.frame) + 10, ScreenWidth, 108)];
        }
    }
}

-(UIView *)createGroupItem:(int) tag{
    UIView *item = [[UIView alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-30, 60)];
    item.tag =tag;
    
    UIImageView *imgView  = [self createImageView];
    [imgView setFrame:CGRectMake(6, 0, 4, 60)];
    [imgView setContentMode:UIViewContentModeCenter];
    [imgView setImage:[UIImage imageNamed:@"返回 copy 2"]];
    imgView.tag = 0;
    [item addSubview:imgView];
    
    ZTextView *textView1 = [self createTextView];
    [textView1 setFrame:CGRectMake(30, 10, ScreenWidth - 60, 40)];
    [textView1 addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    [textView1 setPlaceholder:@"填写内容"];
    textView1.tag = tag + 1000;
    [item addSubview:textView1];
    
    UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnCancel setImage:[UIImage imageNamed:@"发布 关闭 素材"] forState:0];
    [btnCancel setFrame:CGRectMake(ScreenWidth - 30 - 30, 15, 30, 30)];
    btnCancel.tag = tag + 100;
    [btnCancel addTarget:self action:@selector(delItem:) forControlEvents:UIControlEventTouchUpInside];
    [item addSubview:btnCancel];
    
    return item;
}

-(void)delItem:(UIButton *) btn{
    int curTag = (int)btn.tag - 100;
    UIView *g = btn.superview.superview;
    
    if(g.tag == 1111){
        
        [btn.superview removeFromSuperview];
        
        UIButton *btnAdd = [g viewWithTag:11111];
        CGRect bf = btnAdd.frame;
        bf.origin.y = bf.origin.y - 60;
        btnAdd.frame = bf;
        
        CGRect gf = g.frame;
        gf.size.height = gf.size.height - 60;
        g.frame = gf;
        
        UIView *g2 = [_conentView viewWithTag:2222];
        if(g2!=nil){
            CGRect gf2 = g2.frame;
            gf2.origin.y = gf2.origin.y - 60;
            g2.frame = gf2;
        }
        
        for (UIView *itemV in g.subviews) {
            if(itemV.tag > curTag && ![itemV isKindOfClass:[UIButton class]]){
                CGRect itemF = itemV.frame;
                itemF.origin.y = itemF.origin.y - 60;
                itemV.frame = itemF;
            }
        }
        
    }else{
        [btn.superview removeFromSuperview];
        
        UIButton *btnAdd = [g viewWithTag:22222];
        CGRect bf = btnAdd.frame;
        bf.origin.y = bf.origin.y - 60;
        btnAdd.frame = bf;
        
        CGRect gf = g.frame;
        gf.size.height = gf.size.height - 60;
        g.frame = gf;
        
        for (UIView *itemV in g.subviews) {
            if(itemV.tag > curTag && ![itemV isKindOfClass:[UIButton class]]){
                CGRect itemF = itemV.frame;
                itemF.origin.y = itemF.origin.y - 60;
                itemV.frame = itemF;
            }
        }
    }
    
    CGRect cf = _conentView.frame;
    cf.size.height = cf.size.height - 60;
    [_conentView setFrame:cf];
    
    [_menuScroll setFrame:CGRectMake(0, CGRectGetMaxY(cf) + 10, ScreenWidth, 108)];
    
}

-(void)addItemView:(UIButton *) btn{
    if(btn.tag == 11111){
        CGRect bf = btn.frame;
        
        UIView *g1 = [_conentView viewWithTag:1111];
        UIView *item1 = [self createGroupItem:bf.origin.y/60 + 1];
        [item1 setFrame:CGRectMake(0, bf.origin.y, ScreenWidth - 30, 60)];
        [g1 addSubview:item1];
        
        bf.origin.y = bf.origin.y  + 60;
        btn.frame  = bf;
        
        CGRect g1f = g1.frame;
        g1f.size.height = CGRectGetMaxY(bf);
        g1.frame = g1f;
        
        UIView *gitemView2 = [_conentView viewWithTag:2222];
        if(gitemView2!=nil){
            CGRect f2 = gitemView2.frame;
            f2.origin.y = CGRectGetMaxY(g1f);
            gitemView2.frame = f2;
        }
        
    }else{
        CGRect bf = btn.frame;
        UIView *g1 = [_conentView viewWithTag:2222];
        CGRect g1f = g1.frame;
        
        UIView *item1 = [self createGroupItem:g1f.size.height/60];
        [item1 setFrame:CGRectMake(0, bf.origin.y, ScreenWidth - 30, 60)];
        [g1 addSubview:item1];
        
        bf.origin.y = bf.origin.y  + 60;
        btn.frame  = bf;
        
        g1f.size.height = CGRectGetMaxY(bf);
        g1.frame = g1f;
    }
    CGRect cf = _conentView.frame;
    cf.size.height = cf.size.height + 60;
    [_conentView setFrame:cf];
    
    [_menuScroll setFrame:CGRectMake(0, CGRectGetMaxY(cf) + 10, ScreenWidth, 108)];
}

-(UIButton *) createAddButton{
    UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnCancel setImage:[UIImage imageNamed:@"Group 5"] forState:0];
    [btnCancel setFrame:CGRectMake(0, 15, ScreenWidth - 30, 35)];
    [btnCancel setTitle:@"添加一行" forState:0];
    [btnCancel.titleLabel setFont:FontFiftent];
    [btnCancel setTitleColor:UIColorFromRGB(TextSizeEightColor) forState:0];
    [btnCancel addTarget:self action:@selector(addItemView:) forControlEvents:UIControlEventTouchUpInside];
    return btnCancel;
}

-(void)tagClick:(UIButton *)btn{
    // tag = 1,分类，2标签，3话题，4公开/不公开
    if(btn.tag == 1){
        if(checkType!=nil){
            return;
        }
        ChooseTypeController *vc = [[ChooseTypeController alloc] init];
        [vc setZZChooseResultBlock:^(id tagObj) {
            self->checkType = tagObj;
            
            [btn setTitle:convertToString(self->checkType.cat_name) forState:0];
            
            [self changeSelectType];
        }];
        [self openPushVC:vc];
    }
    if(btn.tag == 2 || btn.tag == 3){
        if(checkType == nil){
            [PopUtil showMessage:@"请先选择分类!"];
            return;
            
        }
        ChooseLabelController *vc = [[ChooseLabelController alloc] init];
        vc.type = (int)btn.tag;
        vc.entity = checkType;
        [vc setZZChooseResultBlock:^(id tagObj) {
            NavTypeEntity *typeItem = tagObj;
            BOOL isHad = NO;
            for (NavTypeEntity *item in _labels) {
                if([typeItem.tag_id isEqual:item.tag_id]){
                    isHad = YES;
                    break;
                }
            }
            
            if(!isHad){
                [_labels addObject:tagObj];
                [self reSetButtonLocation];
            }
            
        }];
        [self openPushVC:vc];
    }
}


-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)reSetButtonLocation{
    // 获取标签的控件
    UIButton *btnLabel = [_menuScroll viewWithTag:2];
    
    // 是否公开按钮
    UIButton *btnSecret = [_menuScroll viewWithTag:4];
    
    for (MyButton *btn in _menuScroll.subviews) {
        if(btn.tag >= 100){
            [btn removeFromSuperview];
        }
    }
    
    CGRect sf = CGRectMake(118, 0, 88, 30);
    if(_type == 3){
        sf = CGRectMake(20, 0, 88, 30);
    }
    
    CGFloat x = sf.origin.x;
    CGFloat y = sf.origin.y;
    
    for (int i = 0; i<_labels.count; i++) {
        NavTypeEntity *entity = [_labels objectAtIndex:i];
        MyButton *btn = [MyButton buttonWithType:UIButtonTypeCustom];
        [btn.titleLabel setFont:FontFiftent];
        [btn setTitleColor:UIColorFromRGB(TextSizeEightColor) forState:0];
        btn.layer.cornerRadius = 8.0f;
        btn.layer.masksToBounds = YES;
        btn.layer.borderWidth = 1.0f;
        btn.layer.borderColor = UIColorFromRGB(BgListSectionColor).CGColor;
        btn.objTag = entity;
        btn.tag = 100+i;
        [btn setTitle:[NSString stringWithFormat:@"%@ x",entity.tag_name] forState:0];
        [btn addTarget:self action:@selector(closeTagButton:) forControlEvents:UIControlEventTouchUpInside];
        
        CGSize s = [self autoWidthOfLabel:btn.titleLabel with:sf.size.height];
        if(ScreenWidth - x - s.width > 30){
            [btn setFrame:CGRectMake(x, y, s.width+10, sf.size.height)];
        }else{
            y = y + 40;
            x = 20;
            [btn setFrame:CGRectMake(x, y, s.width+10, sf.size.height)];
        }
        x = x + s.width + 20;
        
        [_menuScroll addSubview:btn];
    }
    
    if(ScreenWidth - x - 88 < 10){
        y = y + 40;
        x = 20;
    }
    [btnLabel setFrame:CGRectMake(x, y, 88, 30)];
    x = x + 88 + 10;
    
    if(btnSecret){
        if(ScreenWidth - x - 88 > 10){
            [btnSecret setFrame:CGRectMake(x, y, 88, 30)];
        }else{
            y = y + 40;
            x = 20;
            [btnSecret setFrame:CGRectMake(x, y, 88, 30)];
        }
    }
}

-(void)closeTagButton:(MyButton *) btn{
    NavTypeEntity *obj = btn.objTag;
    [_labels removeObject:obj];
    [self reSetButtonLocation];
}

-(UIButton *)createShareButton:(int) i{
    CGFloat itemW = 108;
    CGFloat x = 20 + (i-1)*itemW + (i-1)*10;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
    [btn setFrame:CGRectMake(x, 0, itemW, itemW)];
    btn.tag = i;
    btn.layer.cornerRadius = 3.0f;
    btn.layer.masksToBounds  = YES;
    [btn setTitleColor:DEEP_GRAY_COLOR forState:UIControlStateNormal];
    [btn.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [btn setImage:[UIImage imageNamed:@"发布 添加图片"] forState:0];
    [btn addTarget:self action:@selector(addWithButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [_mainScroll addSubview:btn];
    
    [_mainScroll setContentSize:CGSizeMake(x + 108, 108)];
    
    curBtn = btn;
    
    return btn;
}

-(void)addWithButton:(UIButton *) btn{
    if(_waitUploadData.count > 0 && btn.tag <= _waitUploadData.count){
        UIImageView *_picView = (UIImageView*)btn.imageView;
        
        CALayer *calayer = _picView.layer.mask;
        [_picView.layer.mask removeFromSuperlayer];
        
        XHImageViewer *xh = [[XHImageViewer alloc] initWithImageViewerWillDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
            
        } didDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
            
            selectedView.layer.mask = calayer;
            [selectedView setNeedsDisplay];
            
            [btn sendSubviewToBack:_picView];
            
        } didChangeToImageViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
        }];
        
        NSMutableArray *photos = [[NSMutableArray alloc] init];
        [photos addObject:_picView];
        
        //    xh.delegate = self;
        xh.disableTouchDismiss = NO;
        [xh showWithImageViews:photos selectedView:_picView];
        return;
    }
    
    
    [[ImagePickerUtil defaultPicker] startPickerWithController:self title:@"选择图片" checkBlock:^(UIImagePickerControllerSourceType type) {
        if(type == UIImagePickerControllerSourceTypePhotoLibrary){
            
            RITLPhotosViewController *photoController = [RITLPhotosViewController photosViewController];
            photoController.configuration.maxCount = 25;//最大的选择数目
            photoController.configuration.containVideo = false;//选择类型，目前只选择图片不选择视频
            photoController.photo_delegate = self;
            photoController.thumbnailSize = btn.frame.size;//缩略图的尺寸
            
            [self presentViewController:photoController animated:true completion:^{}];
        }
    }];
    
    curBtn = btn;
}
/**
 选中图片以及视频等资源的数据
 根据是否选中原图所得
 如果为原图，则返回原图大小的数据
 如果不是原图，则返回原始比例的数据
 注: 不会返回thumbnailImages的数据大小
 
 @param viewController RITLPhotosViewController
 @param datas 选中资源的数据
 */
- (void)photosViewController:(UIViewController *)viewController
                       datas:(NSArray <NSData *> *)datas{
    for(NSData *data in datas){
        [curBtn setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
        
        UIImageView *imgView = [self createImageView];
        imgView.tag = curBtn.tag + 100;
        [imgView setImage:[UIImage imageNamed:@"发布 关闭 素材"]];
        [imgView setFrame:CGRectMake(108-30, 0, 30, 30)];
        imgView.userInteractionEnabled = YES;
        [imgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(delClick:)]];
        [curBtn addSubview:imgView];
        
        NSData *data1 = UIImageJPEGRepresentation([UIImage imageWithData:data], 0.5);
        [_waitUploadData addObject:data1];
        [self createShareButton:_waitUploadData.count + 1];
    }
}
- (void)photosViewController:(UIViewController *)viewController
                      images:(NSArray <UIImage *> *)images{
    
}


-(void)delClick:(UITapGestureRecognizer *) tap{
    UIImageView *img = (UIImageView *)tap.view;
    int tag = (int)img.tag - 100;
    if(_waitUploadData.count > 0 && tag <= _waitUploadData.count){
        [[AlertUtil shareInstance] showSheet:@"删除图片吗？" message:@"" cancelTitle:@"取消" titleArray:@[@"删除"] viewController:self confirm:^(NSInteger buttonTag) {
            
            if(buttonTag<0){
                // 取消
            }else if(buttonTag == 0){
                UIButton *btn = [self.mainScroll viewWithTag:tag];
                int index = (int)tag+1;
                int count = (int)self.waitUploadData.count + 1;
                
                [btn removeFromSuperview];
                
                for(int i = index;i<=count;i++){
                    UIButton *button = [self.mainScroll viewWithTag:i];
                    UIImageView *img = [button viewWithTag:button.tag+100];
                    if(img){
                        img.tag = img.tag - 1;
                    }
                    button.tag = button.tag - 1;
                    
                    CGRect f = button.frame;
                    f.origin.x = f.origin.x - 118;
                    button.frame = f;
                }
                [self.photos removeObjectForKey:self.waitUploadData[btn.tag - 1]];
                [self.waitUploadData removeObjectAtIndex:btn.tag-1];
            }
        }];
        return;
    }
}

#pragma mark - imageView delegate
- (void)imagePickerDidFinishedWithInfo:(NSDictionary *)info image:(UIImage *)thumIamge file:(NSURL *)url type:(ImagePickerDelegateType)type{
    
    NSData *data = UIImageJPEGRepresentation(thumIamge,0.5);
//    OssUploadType ossType = OssUploadTypeImage;
    if(type == ImagePickerDelegateImage){
        [curBtn setImage:thumIamge forState:UIControlStateNormal];
        
        UIImageView *imgView = [self createImageView];
        imgView.tag = curBtn.tag + 100;
        [imgView setImage:[UIImage imageNamed:@"发布 关闭 素材"]];
        [imgView setFrame:CGRectMake(108-30, 0, 30, 30)];
        imgView.userInteractionEnabled = YES;
        [imgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(delClick:)]];
        [curBtn addSubview:imgView];
        
        [_waitUploadData addObject:data];
        
        [self createShareButton:(int)_waitUploadData.count + 1];
    }
}

-(void)uploadImages{
    if(self.waitUploadData.count == _photos.allKeys.count){
        [self publishSucai];
        return;
    }
    
    
    [self.waitUploadData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSData *data = obj;
        if([self->_photos objectForKey:obj]==nil){
            NSString *nav_type = self->checkType.nav_type;
            if([@"skin" isEqual:nav_type]){
                nav_type = @"skins";
            }
            [ImageUploadUtil updateImage:data type:convertToString(nav_type) callback:^(NSString *imageurl, NSDictionary *videoDict,NSString *message) {
                DLog(@"%@",imageurl);
                NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:videoDict];
                [params setObject:data forKey:@"data"];
                if(convertToString(imageurl).length==0){
                    [PopUtil showMessage:message positionType:PopPositionTypeMiddle];
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    
                    // 跳出循环
                    *stop = YES;
                }else{
                    [self->_photos setObject:videoDict forKey:obj];
            
                    if(idx == self.waitUploadData.count -1){
                    
//                        if(self.waitUploadData.count == [self->_photos allKeys].count){
                            [self publishSucai];
//                       }
                    }
                }
            }];
        }
    }];
}



#pragma mark - textview delegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.markedTextRange == nil) {
        textView.attributedText = [textView.text formatWithParagraph:5.0 fontSize:15 textColor:[UIColor blackColor]];
    }
}



-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self allHideKeyBoard];
}

- (void)allHideKeyBoard
{
    for (UIWindow* window in [UIApplication sharedApplication].windows)
    {
        for (UIView* view in window.subviews)
        {
            [self dismissAllKeyBoardInView:view];
        }
    }
}

-(BOOL) dismissAllKeyBoardInView:(UIView *)view
{
    if([view isFirstResponder])
    {
        [view resignFirstResponder];
        return YES;
    }
    for(UIView *subView in view.subviews)
    {
        if([self dismissAllKeyBoardInView:subView])
        {
            return YES;
        }
    }
    return NO;
}

// 隐藏键盘
-(void)downKeyBoard:(id)sender{
    [self allHideKeyBoard];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    
    if ([touch.view isKindOfClass:[UIScrollView class]]) {
        
        return YES;
        
    }
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//请登录
-(void)showLogin{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录一下，让更多的人看到你" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *login = [UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoginController *loginVC = [[LoginController alloc] init];
        [self addChildViewController:loginVC];
        [self.navigationController pushViewController:loginVC animated:YES];
    }];
    [alert addAction:cancle];
    [alert addAction:login];
    [self presentViewController:alert animated:YES completion:nil];
}
@end
